import { ExecutionContext, UseFilters } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { Args, Int, Mutation, Query, Resolver } from '@nestjs/graphql';
import { User } from './user.decorator';
import { UserEntity } from './user.entity';
import { UserService } from './user.service';
import { GrpcFilter } from 'src/common/grpc/grpc.filter';
import { AddonException } from 'src/common/exception/story.exception';
import { jwtKey } from 'src/common/auth/auth.guard';

@UseFilters(GrpcFilter)
@Resolver(() => UserEntity)
export class UserResolver {
  constructor(private readonly userService: UserService) {}

  @Query(() => UserEntity)
  async user(@Args('_id') _id: string): Promise<UserEntity> {
    return this.userService.findUser(_id);
  }

  @Mutation(() => String)
  async login(
    @User() user: UserEntity,
    @Args('userName') userName: string,
    @Args('password') password: string,
  ): Promise<string> {
    if (user._id) {
      throw new AddonException('你已经登录了。');
    }

    const u = await this.userService.findUserByUserName(userName);
    if (!u) {
      throw new AddonException('用户不存在！');
    }
    if (u.password !== password) {
      throw new AddonException('密码错误！');
    }
    return jwt.sign({ _id: u._id }, jwtKey);
  }

  @Mutation(() => UserEntity)
  async register(
    @User() user: UserEntity,
    @Args('userName', { type: () => String }) userName: string,
    @Args('password', { type: () => String }) password: string,
  ): Promise<UserEntity> {
    if (user._id) {
      throw new AddonException('你已经登录了。');
    }
    return this.userService.createUser({ userName, password });
  }
}
